package xiaolong.arithmetic.fun_lib;

import java.util.HashMap;

/**
 * Created by xinxiaolong on 2020/10/29.
 * email：xinxiaolong123@foxmail.com
 * <p>
 * 反转一个单链表。
 * <p>
 * 示例:
 * <p>
 * 输入: 1->2->3->4->5
 * 输出: 5->4->3->2->1
 * 进阶:
 * 你可以迭代或递归地反转链表。你能否用两种方法解决这道题？
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/reverse-linked-list
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class ReverseList {


    public static void main(String[] arg) {
        String[] array = new String[]{"1", "2", "3", "4", "5"};
        ListNode node = arrayToListNode(array);
        printNode(node);
    }

    public static class ListNode {
        String val;
        ListNode next;

        ListNode(String x) {
            val = x;
        }
    }

    public ListNode reverseList(ListNode head) {
        ListNode mHead=null;
        ListNode pre =null;
        ListNode last=null;
        while (head.next!=null){

            if(mHead==null){
                mHead=new ListNode(head.val);
                pre=mHead;
            }else {
                pre=head.next;
            }

        }

        return pre;
    }

    public static ListNode arrayToListNode(String[] array) {
        ListNode head = null;
        ListNode pre = null;

        if (array == null) {
            return head;
        }

        for (String str : array) {
            if (head == null) {
                head = new ListNode(str);
                pre = head;
            } else {
                pre.next = new ListNode(str);
                pre=pre.next;
            }
        }
        return head;
    }

    public static void printNode(ListNode node) {
        while (node != null) {
            System.out.print(node.val+"   ");
            node = node.next;
        }
    }
}
